/*
 * Created on 2005-5-16
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dcivision.form.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRoutingRule;
import com.dcivision.form.bean.MtmFormPageFormSection;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormRoutingRuleDAObject;
import com.dcivision.form.dao.FormSelectionFieldDAObject;
import com.dcivision.form.dao.FormSelectionFieldOptionDAObject;
import com.dcivision.form.dao.MtmFormPageFormSectionDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.workflow.bean.WorkflowStepFormEquat;
import com.dcivision.workflow.dao.MtmWorkflowRecordObjectLinkDAObject;

/**
 * @author Administrator
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MaintFormRoutingRuleAction extends com.dcivision.framework.web.AbstractMaintAction {


  /** getFunctionCode
   *
   * Abstract function which sub-class should implement to return the corresponding
   * function code.
   *
   * @return   The function code
   */
  public String getFunctionCode() {
    return SystemFunctionConstant.FORM_SETUP;
  }

  /** getMajorDAOClassName
   *
   * Abstract function which sub-class should implement to return the corresponding
   * major DAO class name used in this class.
   *
   * @return   The DAO class name
   */
  public String getMajorDAOClassName() {
    return "com.dcivision.form.dao.FormRoutingRuleDAObject";
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;

    String opMode = (maintForm != null) ? maintForm.getOpMode() : request.getParameter("opMode"); //maintForm.getOpMode();
    String navMode = (maintForm != null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
   
    if (GlobalConstant.NAV_MODE_NEW.equals(navMode)){
      FormRoutingRuleDAObject formRoutingRuleDAO = new FormRoutingRuleDAObject(this.getSessionContainer(request),this.getConnection(request));
      List routingRuleList = formRoutingRuleDAO.getListByFormRecordID(maintForm.getFormRecordID());
      navMode = routingRuleList.size()>0 ? GlobalConstant.NAV_MODE_EDIT : GlobalConstant.NAV_MODE_NEW;
      maintForm.setNavMode(navMode);
    }
    refreshFormData(mapping, maintForm, request, response);
    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward != null) {
        return forward;
      }
      
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    }     
    return super.execute(mapping, form, request, response);   
  }

  public void refreshFormData(
        ActionMapping mapping, 
        AbstractActionForm form, 
        HttpServletRequest request, 
        HttpServletResponse response) 
  throws ApplicationException {
    List formElementList = new ArrayList();
    List targetFormElementList = new ArrayList();
    List formRecordList = new ArrayList();
    String optionElementIDs = "";
    
    try {
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      MtmWorkflowRecordObjectLinkDAObject objectLinkDAO = new MtmWorkflowRecordObjectLinkDAObject(sessionContainer,conn);
      FormRecordDAObject formRecordDAO = new FormRecordDAObject(sessionContainer,conn);
      FormPageDAObject formPageDAO = new FormPageDAObject(sessionContainer,conn);
      FormElementDAObject formElementDAO = new FormElementDAObject(sessionContainer,conn);
      FormSelectionFieldDAObject fieldDAO = new FormSelectionFieldDAObject(sessionContainer,conn);
      FormSelectionFieldOptionDAObject optionDAO = new FormSelectionFieldOptionDAObject(sessionContainer,conn); 
            
      MtmFormPageFormSectionDAObject pageSectionDAO = new MtmFormPageFormSectionDAObject(sessionContainer,conn);
      MtmFormSectionFormElementDAObject sectionElementDAO = new MtmFormSectionFormElementDAObject(sessionContainer,conn);
      
      MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;
      
      String formEquationListValue = maintForm.getFormEquationListValue();
      String[] formEquationArr = null;
      String formEquationItem = maintForm.getFormEquationItem();
      String haveNumber = "false";
      String haveDate = "false";

      //get the formElementList    
      Integer formRecordID = null;
      if( !Utility.isEmpty(maintForm.getFormRecordID()) ){
        formRecordID = new Integer( maintForm.getFormRecordID() );
      }
      
      if(!Utility.isEmpty(formRecordID)){
        List formPageList = formPageDAO.getDetailListByFormRecordID(formRecordID);
        for(int j=0; j<formPageList.size(); j++){
          FormPage formPage = (FormPage)formPageList.get(j);
          List pageSectionList = pageSectionDAO.getListByPageID(formPage.getID());
          for (int k=0; k<pageSectionList.size(); k++){
            MtmFormPageFormSection pageSection = (MtmFormPageFormSection)pageSectionList.get(k);
            List sectionElementList = sectionElementDAO.getListBySectionID(pageSection.getSectionID());
            for(int n=0; n<sectionElementList.size(); n++){
              MtmFormSectionFormElement sectionElement = (MtmFormSectionFormElement)sectionElementList.get(n);
              FormElement formElement = (FormElement)formElementDAO.getObjectByID(sectionElement.getElementID());
              if(FormElementType.ELEMENT_TEXT.equals(formElement.getElementType()) ||
              		FormElementType.ELEMENT_TEXT_AREA.equals(formElement.getElementType()) ||
									FormElementType.ELEMENT_DATE_PICKER.equals(formElement.getElementType()) ||
									FormElementType.ELEMENT_CHECK_BOX.equals(formElement.getElementType()) || 
									FormElementType.ELEMENT_SELECTION_BOX.equals(formElement.getElementType()) ||
									FormElementType.ELEMENT_RADIO_BUTTON.equals(formElement.getElementType()) ){
              	
              	formElement.setFormRecordID(formRecordID.toString());
              	formElement.setFormPageID(formPage.getID().toString());
              	formElement.setFormSectionID(pageSection.getSectionID().toString());
              	targetFormElementList.add(formElement);     
                if (FormElementType.ELEMENT_DATE_PICKER.equals(formElement.getElementType()) ){
                  haveDate = "true";   
                }
                if(FormElementType.ELEMENT_TEXT.equals(formElement.getElementType()) 
                    && (FormElement.VALIDATION_INTEGER_ONLY.equals(formElement.getValidationRule()) || 
                        FormElement.VALIDATION_NUMERIC_ONLY.equals(formElement.getValidationRule()) )){
                  haveNumber = "true";   
                }
              } 
              if(!Utility.isEmpty(maintForm.getRuleType()) && FormRoutingRule.ROUTING_TYPE_CALCULATE.equals(maintForm.getRuleType())){
                if(FormElementType.ELEMENT_TEXT.equals(formElement.getElementType()) 
                        && (FormElement.VALIDATION_INTEGER_ONLY.equals(formElement.getValidationRule()) || 
                            FormElement.VALIDATION_NUMERIC_ONLY.equals(formElement.getValidationRule()) )){
                  formElement.setFormRecordID(formRecordID.toString());
                  formElement.setFormPageID(formPage.getID().toString());
                  formElement.setFormSectionID(pageSection.getSectionID().toString());
                  formElementList.add(formElement);  
                }
              }else {
                if(!Utility.isEmpty(maintForm.getOperationType()) && WorkflowStepFormEquat.OPERATION_TYPE_NUMBER.equals(maintForm.getOperationType())){
                  if(FormElementType.ELEMENT_TEXT.equals(formElement.getElementType()) 
                      && (FormElement.VALIDATION_INTEGER_ONLY.equals(formElement.getValidationRule()) || 
                          FormElement.VALIDATION_NUMERIC_ONLY.equals(formElement.getValidationRule()) )){
                    formElement.setFormRecordID(formRecordID.toString());
                    formElement.setFormPageID(formPage.getID().toString());
                    formElement.setFormSectionID(pageSection.getSectionID().toString());
                    formElementList.add(formElement);  
                    maintForm.setOperationType(WorkflowStepFormEquat.OPERATION_TYPE_NUMBER);
                  }
                }else if(!Utility.isEmpty(maintForm.getOperationType()) && WorkflowStepFormEquat.OPERATION_TYPE_DATE.equals(maintForm.getOperationType())){  
                  if(FormElementType.ELEMENT_DATE_PICKER.equals(formElement.getElementType()) ||
                           FormElementType.ELEMENT_CURRENT_DATE.equals(formElement.getElementType()) ){ 
                    formElement.setFormRecordID(formRecordID.toString());
                    formElement.setFormPageID(formPage.getID().toString());
                    formElement.setFormSectionID(pageSection.getSectionID().toString());
                    formElementList.add(formElement);
                  }
                }else{
                	if(FormElementType.ELEMENT_TEXT.equals(formElement.getElementType()) ||
                			FormElementType.ELEMENT_TEXT_AREA.equals(formElement.getElementType()) ||
											FormElementType.ELEMENT_DATE_PICKER.equals(formElement.getElementType()) ||
											FormElementType.ELEMENT_CHECK_BOX.equals(formElement.getElementType()) || 
											FormElementType.ELEMENT_SELECTION_BOX.equals(formElement.getElementType()) ||
											FormElementType.ELEMENT_RADIO_BUTTON.equals(formElement.getElementType()) ){
                		
                		formElement.setFormRecordID(formRecordID.toString());
                		formElement.setFormPageID(formPage.getID().toString());
                		formElement.setFormSectionID(pageSection.getSectionID().toString());
                		formElementList.add(formElement);
                		
                		if(FormElementType.isSelection(formElement.getElementType())){
                			optionElementIDs +=  WorkflowStepFormEquat.ELEMENT_PREFIX_CHAR + formElement.getID() + ",";
                		}              		
                	}  
                }
              }             
            }
          }
        }
      }
       
      
      if(!Utility.isEmpty(formEquationListValue)){
        formEquationArr = TextUtility.splitString(formEquationListValue,"$$");
      }
      
      String[] deleteItemArr = request.getParameterValues("deleteItem");
      boolean checked = false;
      formEquationListValue = "";
      
      int startValue = !Utility.isEmpty(formEquationArr)&&!Utility.isEmpty(formEquationArr[0]) ? 0 : 1;
      for(int j=0; !Utility.isEmpty(formEquationArr) &&  j<formEquationArr.length; j++){
        checked = false;
        for(int i=0; !Utility.isEmpty(deleteItemArr) && i<deleteItemArr.length; i++){
          if(j == Integer.parseInt(deleteItemArr[i])+startValue){
            checked = true;
            break;
          }    
        }
        if(!checked){          
          if(Utility.isEmpty(formEquationListValue)){
            formEquationListValue += formEquationArr[j];  
          }else{
            formEquationListValue += "$$" + formEquationArr[j];
          }
        }
      }
      
      if(Utility.isEmpty(formEquationListValue) && !Utility.isEmpty(formEquationItem) ){
        formEquationListValue = formEquationItem;
      } else if(!Utility.isEmpty(formEquationItem)) {
        formEquationListValue += "$$" + formEquationItem;  
      }
            
      //get the options
      List optionList = new ArrayList();
      if(!Utility.isEmpty(formElementList) ){
        FormElement formElement = (FormElement)formElementList.get(0);
        maintForm.setFormElementStr( WorkflowStepFormEquat.ELEMENT_PREFIX_CHAR + formElement.getID() );
      }
      
      if( !Utility.isEmpty(maintForm.getFormElementStr()) ){
        String elementID = maintForm.getFormElementStr().substring(1);
        FormElement element = (FormElement) formElementDAO.getObjectByID(new Integer(elementID));
        maintForm.setFormElement(element);
      }      
      
      maintForm.setRouteNameListValue(maintForm.getRouteNameListValue());      
      maintForm.setFormEquationListValue(formEquationListValue);
      maintForm.setOptionElementIDs(optionElementIDs);
      maintForm.setFormRecordID(formRecordID.toString());
      
      request.setAttribute("formElementList", formElementList);
      request.setAttribute("targetFormElementList", targetFormElementList);
      request.setAttribute("optionList", optionList);
      request.setAttribute("haveNumber",haveNumber);
      request.setAttribute("haveDate",haveDate);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  public void insertRecord(ActionMapping mapping,
  		AbstractActionForm form,
			HttpServletRequest request,
			HttpServletResponse response)
    throws ApplicationException {
    
    MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;
    FormRoutingRuleDAObject formRoutingRuleDAO = new FormRoutingRuleDAObject(this.getSessionContainer(request), this.getConnection(request));

  	String formEquationListValue = maintForm.getFormEquationListValue();
    FormRoutingRule formRoutingRule = new FormRoutingRule();
  	if(!Utility.isEmpty(formEquationListValue)){
  		String[] formEquationItemArr = TextUtility.splitString(formEquationListValue,"$$");
  		for(int i=0; i<formEquationItemArr.length; i++){
  			String[] elementArr = TextUtility.splitString(formEquationItemArr[i],";");	
  			formRoutingRule.setFormRecordID(TextUtility.parseIntegerObj(maintForm.getFormRecordID()));
  			formRoutingRule.setRuleName(elementArr[0]);
  			formRoutingRule.setRuleType(elementArr[1]);
  			formRoutingRule.setOperationType(elementArr[2]);
  			formRoutingRule.setFormEquation(elementArr[3]);  			
  			formRoutingRule.setFormOperationEquation(elementArr[9]);
  			formRoutingRule.setTargetElementID(elementArr[4]);    
  			formRoutingRule.setCheckRule(elementArr[5]);
  			formRoutingRuleDAO.insertObject(formRoutingRule);
  		}
  	}
  	
    
  }

  public void updateRecord(ActionMapping mapping,
      AbstractActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
    throws ApplicationException {
    
    MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;
    FormRoutingRuleDAObject formRoutingRuleDAO = new FormRoutingRuleDAObject(this.getSessionContainer(request), this.getConnection(request));
    formRoutingRuleDAO.deleteByFormRecordID(new Integer(maintForm.getFormRecordID()));
    
    String formEquationListValue = maintForm.getFormEquationListValue();
    FormRoutingRule formRoutingRule = new FormRoutingRule();
    if(!Utility.isEmpty(formEquationListValue)){
        String[] formEquationItemArr = TextUtility.splitString(formEquationListValue,"$$");
        for(int i=0; i<formEquationItemArr.length; i++){
            String[] elementArr = TextUtility.splitString(formEquationItemArr[i],";");  
            formRoutingRule.setFormRecordID(TextUtility.parseIntegerObj(maintForm.getFormRecordID()));
            formRoutingRule.setRuleName(elementArr[0]);
            formRoutingRule.setRuleType(elementArr[1]);
            formRoutingRule.setOperationType(elementArr[2]);
            formRoutingRule.setFormEquation(elementArr[3]);             
            formRoutingRule.setFormOperationEquation(elementArr[9]);
            formRoutingRule.setTargetElementID(elementArr[4]);    
            formRoutingRule.setCheckRule(elementArr[5]);
            formRoutingRuleDAO.insertObject(formRoutingRule);
        }
    }
  }
  
  public void selectRecord(ActionMapping mapping,
      AbstractActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
    throws ApplicationException {
    
    MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;
    if (!Utility.isEmpty(request.getParameter("formRecordID")) && !"null".equals(request.getParameter("formRecordID"))){
      maintForm.setFormRecordID(request.getParameter("formRecordID"));   
    }
    FormRoutingRuleDAObject formRoutingRuleDAO = new FormRoutingRuleDAObject(this.getSessionContainer(request),this.getConnection(request));
    FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request),this.getConnection(request));
    List routingRuleList = formRoutingRuleDAO.getListByFormRecordID(maintForm.getFormRecordID());
    String formEquationListValue = "";
    String formEquationItem = "";
    String displayRuleType = "",displayTargetElement = "",displayCheckRule="";
    
    for (int i=0; i<routingRuleList.size(); i++){
       
      FormRoutingRule formRoutingRule = (FormRoutingRule)routingRuleList.get(i);
      displayRuleType = FormRoutingRule.ROUTING_TYPE_CALCULATE.equals(formRoutingRule.getRuleType()) ? MessageResourcesFactory.getMessage(this.getLocale(request),"form.label.calculate_rule") : MessageResourcesFactory.getMessage(this.getLocale(request),"form.label.verify_rule");
      displayCheckRule = formRoutingRule.getCheckRule().equals(FormRoutingRule.CHECK_RULE_MANDATORY) ? MessageResourcesFactory.getMessage(this.getLocale(request),"common.label.mandatory"): "" ;
      if (!Utility.isEmpty(formRoutingRule.getTargetElementID()) && !"null".equals(formRoutingRule.getTargetElementID())){
        String[] elementStr = TextUtility.splitString(formRoutingRule.getTargetElementID().substring(1,formRoutingRule.getTargetElementID().length()),"_"); 
        FormElement formElement = (FormElement)formElementDAO.getObjectByID(new Integer(elementStr[4]));
        displayTargetElement = formElement.getFieldName();
      }
      formEquationItem = formRoutingRule.getRuleName() + ";" +     
			  formRoutingRule.getRuleType() + ";" +   
			  formRoutingRule.getOperationType() + ";" +  
			  (String)formRoutingRule.getFormEquation() + ";" +			  
			  formRoutingRule.getTargetElementID() + ";" +
			  formRoutingRule.getCheckRule() + ";" +
        displayRuleType + ";" +
        displayTargetElement + ";" +
        displayCheckRule + ";" +         
        (String)formRoutingRule.getFormOperationEquation() ;    
   
      formEquationListValue += "$$" + formEquationItem;
      maintForm.setID(formRoutingRule.getID().toString());
    }
    maintForm.setFormEquationListValue(formEquationListValue);
    
    refreshFormData(mapping, form, request, response);
  }
  
  public void deleteRecord(ActionMapping mapping,
      AbstractActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
    throws ApplicationException {
    
    MaintFormRoutingRuleForm maintForm = (MaintFormRoutingRuleForm)form;
    FormRoutingRuleDAObject formRoutingRuleDAO = new FormRoutingRuleDAObject(this.getSessionContainer(request), this.getConnection(request));

    formRoutingRuleDAO.deleteByFormRecordID(new Integer(maintForm.getFormRecordID()));
    
  }
}
